import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { v4 as uuidv4 } from 'uuid'
import type { ComponentConfig, CanvasState, HistoryRecord, PageConfig, PageState } from '@/types/component'

export const useCanvasStore = defineStore('canvas', () => {
  // 页面状态
  const pageState = ref<PageState>({
    pages: [],
    currentPageId: null
  })

  // 画布状态
  const canvasState = ref<CanvasState>({
    components: [],
    selectedComponentIds: [],
    scale: 1,
    gridSize: 20,
    showGrid: true
  })

  // 历史记录
  const history = ref<HistoryRecord[]>([])
  const historyIndex = ref(-1)

  // 计算属性
  const selectedComponents = computed(() => {
    return canvasState.value.components.filter(
      comp => canvasState.value.selectedComponentIds.includes(comp.id)
    )
  })

  const selectedComponent = computed(() => {
    const selected = selectedComponents.value
    return selected.length === 1 ? selected[0] : null
  })

  const canUndo = computed(() => historyIndex.value > 0)
  const canRedo = computed(() => historyIndex.value < history.value.length - 1)

  // 保存当前页面组件到页面配置（前置声明）
  const saveCurrentPageComponents = () => {
    if (!pageState.value.currentPageId) return
    
    const page = pageState.value.pages.find(p => p.id === pageState.value.currentPageId)
    if (page) {
      page.components = JSON.parse(JSON.stringify(canvasState.value.components))
      page.updatedAt = Date.now()
    }
  }

  // 保存历史记录
  const saveHistory = (description: string) => {
    // 移除当前位置之后的历史记录
    history.value = history.value.slice(0, historyIndex.value + 1)
    
    // 添加新的历史记录
    const record: HistoryRecord = {
      id: uuidv4(),
      timestamp: Date.now(),
      components: JSON.parse(JSON.stringify(canvasState.value.components)),
      description
    }
    
    history.value.push(record)
    historyIndex.value = history.value.length - 1
    
    // 限制历史记录数量
    if (history.value.length > 50) {
      history.value.shift()
      historyIndex.value--
    }
    
    // 自动保存到当前页面
    saveCurrentPageComponents()
  }

  // 添加组件
  const addComponent = (component: ComponentConfig) => {
    canvasState.value.components.push(component)
    canvasState.value.selectedComponentIds = [component.id]
    saveHistory(`添加组件: ${component.type}`)
  }

  // 删除组件
  const removeComponent = (componentId: string) => {
    const index = canvasState.value.components.findIndex(comp => comp.id === componentId)
    if (index > -1) {
      const component = canvasState.value.components[index]
      canvasState.value.components.splice(index, 1)
      canvasState.value.selectedComponentIds = canvasState.value.selectedComponentIds.filter(id => id !== componentId)
      saveHistory(`删除组件: ${component.type}`)
    }
  }

  // 删除选中的组件
  const removeSelectedComponents = () => {
    const selectedIds = [...canvasState.value.selectedComponentIds]
    selectedIds.forEach(id => {
      const index = canvasState.value.components.findIndex(comp => comp.id === id)
      if (index > -1) {
        canvasState.value.components.splice(index, 1)
      }
    })
    canvasState.value.selectedComponentIds = []
    saveHistory(`删除${selectedIds.length}个组件`)
  }

  // 更新组件
  const updateComponent = (componentId: string, updates: Partial<ComponentConfig>) => {
    const component = canvasState.value.components.find(comp => comp.id === componentId)
    if (component) {
      Object.assign(component, updates)
      saveHistory(`更新组件: ${component.type}`)
    }
  }

  // 选中组件
  const selectComponent = (componentId: string | null, isCtrlPressed = false) => {
    if (!componentId) {
      canvasState.value.selectedComponentIds = []
      return
    }

    if (isCtrlPressed) {
      // Ctrl+点击，切换选中状态
      const index = canvasState.value.selectedComponentIds.indexOf(componentId)
      if (index > -1) {
        canvasState.value.selectedComponentIds.splice(index, 1)
      } else {
        canvasState.value.selectedComponentIds.push(componentId)
      }
    } else {
      // 普通点击，只选中当前组件
      canvasState.value.selectedComponentIds = [componentId]
    }
  }

  // 选中多个组件
  const selectMultipleComponents = (componentIds: string[]) => {
    canvasState.value.selectedComponentIds = [...componentIds]
    console.log('选中多个组件', canvasState.value.selectedComponentIds)
  }

  // 移动组件
  const moveComponent = (componentId: string, position: { x: number; y: number }) => {
    const component = canvasState.value.components.find(comp => comp.id === componentId)
    if (component) {
      component.position = position
    }
  }

  // 调整组件大小
  const resizeComponent = (componentId: string, size: { width: number; height: number }) => {
    const component = canvasState.value.components.find(comp => comp.id === componentId)
    if (component) {
      component.size = size
    }
  }

  // 撤销
  const undo = () => {
    if (canUndo.value) {
      historyIndex.value--
      canvasState.value.components = JSON.parse(JSON.stringify(history.value[historyIndex.value].components))
      canvasState.value.selectedComponentIds = []
      // 撤销后也需要保存到当前页面
      saveCurrentPageComponents()
    }
  }

  // 重做
  const redo = () => {
    if (canRedo.value) {
      historyIndex.value++
      canvasState.value.components = JSON.parse(JSON.stringify(history.value[historyIndex.value].components))
      canvasState.value.selectedComponentIds = []
      // 重做后也需要保存到当前页面
      saveCurrentPageComponents()
    }
  }

  // 清空画布
  const clearCanvas = () => {
    canvasState.value.components = []
    canvasState.value.selectedComponentIds = []
    saveHistory('清空画布')
  }

  // 导入配置（导入所有页面）
  const importConfig = (config: any) => {
    if (!config.pages || !Array.isArray(config.pages)) {
      throw new Error('配置格式不正确，请确保导入的是有效的 InduPanel 配置文件')
    }
    
    // 导入所有页面
    pageState.value.pages = JSON.parse(JSON.stringify(config.pages))
    
    // 切换到第一个页面
    if (pageState.value.pages.length > 0) {
      pageState.value.currentPageId = pageState.value.pages[0].id
      loadPageComponents(pageState.value.pages[0].id)
    } else {
      // 如果没有页面，创建一个默认页面
      createPage('页面1')
    }
    
    // 重置历史记录
    history.value = []
    historyIndex.value = -1
    saveHistory('导入配置')
  }

  // 导出配置（导出所有页面）
  const exportConfig = () => {
    // 先保存当前页面的组件
    saveCurrentPageComponents()
    
    // 导出所有页面的配置
    return {
      pages: JSON.parse(JSON.stringify(pageState.value.pages)),
      exportTime: Date.now(),
      version: '1.0'
    }
  }

  // 初始化历史记录
  const initHistory = () => {
    // 初始化页面
    initPages()
    
    if (history.value.length === 0) {
      saveHistory('初始化画布')
    }
  }

  // 对齐功能
  const alignComponents = (type: 'left' | 'center' | 'right' | 'top' | 'middle' | 'bottom') => {
    if (canvasState.value.components.length < 2) return

    const components = canvasState.value.components
    let referenceValue: number

    switch (type) {
      case 'left':
        referenceValue = Math.min(...components.map(comp => comp.position?.x || 0))
        components.forEach(comp => {
          if (comp.position) {
            comp.position.x = referenceValue
            comp.style = { ...comp.style, left: `${referenceValue}px` }
          }
        })
        break
      case 'right':
        const rightValues = components.map(comp => (comp.position?.x || 0) + (comp.size?.width || 100))
        referenceValue = Math.max(...rightValues)
        components.forEach(comp => {
          const newX = referenceValue - (comp.size?.width || 100)
          if (comp.position) {
            comp.position.x = newX
            comp.style = { ...comp.style, left: `${newX}px` }
          }
        })
        break
      case 'center':
        const centerValues = components.map(comp => (comp.position?.x || 0) + (comp.size?.width || 100) / 2)
        referenceValue = centerValues.reduce((a, b) => a + b, 0) / centerValues.length
        components.forEach(comp => {
          const newX = referenceValue - (comp.size?.width || 100) / 2
          if (comp.position) {
            comp.position.x = newX
            comp.style = { ...comp.style, left: `${newX}px` }
          }
        })
        break
      case 'top':
        referenceValue = Math.min(...components.map(comp => comp.position?.y || 0))
        components.forEach(comp => {
          if (comp.position) {
            comp.position.y = referenceValue
            comp.style = { ...comp.style, top: `${referenceValue}px` }
          }
        })
        break
      case 'bottom':
        const bottomValues = components.map(comp => (comp.position?.y || 0) + (comp.size?.height || 32))
        referenceValue = Math.max(...bottomValues)
        components.forEach(comp => {
          const newY = referenceValue - (comp.size?.height || 32)
          if (comp.position) {
            comp.position.y = newY
            comp.style = { ...comp.style, top: `${newY}px` }
          }
        })
        break
      case 'middle':
        const middleValues = components.map(comp => (comp.position?.y || 0) + (comp.size?.height || 32) / 2)
        referenceValue = middleValues.reduce((a, b) => a + b, 0) / middleValues.length
        components.forEach(comp => {
          const newY = referenceValue - (comp.size?.height || 32) / 2
          if (comp.position) {
            comp.position.y = newY
            comp.style = { ...comp.style, top: `${newY}px` }
          }
        })
        break
    }
    
    saveHistory(`${type}对齐`)
  }

  // 分布功能
  const distributeComponents = (type: 'horizontal' | 'vertical') => {
    if (canvasState.value.components.length < 3) return

    const components = [...canvasState.value.components]

    if (type === 'horizontal') {
      // 按X坐标排序
      components.sort((a, b) => (a.position?.x || 0) - (b.position?.x || 0))
      
      const leftmost = components[0].position?.x || 0
      const rightmost = (components[components.length - 1].position?.x || 0) + (components[components.length - 1].size?.width || 100)
      const totalSpace = rightmost - leftmost
      const spaceBetween = totalSpace / (components.length - 1)

      components.forEach((comp, index) => {
        if (index > 0 && index < components.length - 1) {
          const newX = leftmost + spaceBetween * index
          if (comp.position) {
            comp.position.x = newX
            comp.style = { ...comp.style, left: `${newX}px` }
          }
        }
      })
    } else {
      // 按Y坐标排序
      components.sort((a, b) => (a.position?.y || 0) - (b.position?.y || 0))
      
      const topmost = components[0].position?.y || 0
      const bottommost = (components[components.length - 1].position?.y || 0) + (components[components.length - 1].size?.height || 32)
      const totalSpace = bottommost - topmost
      const spaceBetween = totalSpace / (components.length - 1)

      components.forEach((comp, index) => {
        if (index > 0 && index < components.length - 1) {
          const newY = topmost + spaceBetween * index
          if (comp.position) {
            comp.position.y = newY
            comp.style = { ...comp.style, top: `${newY}px` }
          }
        }
      })
    }

    saveHistory(`${type === 'horizontal' ? '水平' : '垂直'}分布`)
  }

  // 合并组件
  const groupComponents = (componentIds: string[]) => {
    if (componentIds.length < 2) return

    const componentsToGroup = canvasState.value.components.filter(comp => componentIds.includes(comp.id))
    if (componentsToGroup.length < 2) return

    // 计算包围盒
    const minX = Math.min(...componentsToGroup.map(comp => comp.position?.x || 0))
    const minY = Math.min(...componentsToGroup.map(comp => comp.position?.y || 0))
    const maxX = Math.max(...componentsToGroup.map(comp => (comp.position?.x || 0) + (comp.size?.width || 100)))
    const maxY = Math.max(...componentsToGroup.map(comp => (comp.position?.y || 0) + (comp.size?.height || 32)))

    const groupId = uuidv4()
    
    // 保存相对位置并标记为组合组件
    componentsToGroup.forEach(comp => {
      comp.groupId = groupId
      comp.isGroup = false // 子组件不是组合
      comp.originalPosition = {
        x: (comp.position?.x || 0) - minX,
        y: (comp.position?.y || 0) - minY
      }
    })

    // 创建组合组件
    const groupComponent: ComponentConfig = {
      id: groupId,
      type: 'group',
      props: {
        name: `组合${Math.floor(Math.random() * 1000)}`
      },
      style: {
        position: 'absolute',
        left: `${minX}px`,
        top: `${minY}px`,
        border: '2px dashed #1890ff',
        backgroundColor: 'rgba(24, 144, 255, 0.05)',
        borderRadius: '4px'
      },
      position: { x: minX, y: minY },
      size: { 
        width: maxX - minX,
        height: maxY - minY
      },
      children: componentsToGroup,
      isGroup: true
    }

    // 从画布中移除原组件，添加组合组件
    canvasState.value.components = canvasState.value.components.filter(comp => !componentIds.includes(comp.id))
    canvasState.value.components.push(groupComponent)
    canvasState.value.selectedComponentIds = [groupId]
    
    saveHistory(`合并${componentIds.length}个组件`)
  }

  // 打散组合
  const ungroupComponent = (groupId: string) => {
    const groupComponent = canvasState.value.components.find(comp => comp.id === groupId && comp.type === 'group')
    if (!groupComponent || !groupComponent.children) return

    const groupX = groupComponent.position?.x || 0
    const groupY = groupComponent.position?.y || 0

    // 恢复子组件的绝对位置
    const ungroupedComponents = groupComponent.children.map(child => ({
      ...child,
      position: {
        x: groupX + (child.originalPosition?.x || 0),
        y: groupY + (child.originalPosition?.y || 0)
      },
      style: {
        ...child.style,
        left: `${groupX + (child.originalPosition?.x || 0)}px`,
        top: `${groupY + (child.originalPosition?.y || 0)}px`
      },
      isGroup: undefined,
      groupId: undefined,
      originalPosition: undefined
    }))

    // 从画布中移除组合组件，添加子组件
    canvasState.value.components = canvasState.value.components.filter(comp => comp.id !== groupId)
    canvasState.value.components.push(...ungroupedComponents)
    canvasState.value.selectedComponentIds = ungroupedComponents.map(comp => comp.id)
    
    saveHistory(`打散组合`)
  }

  // ==================== 页面管理功能 ====================
  
  // 当前页面
  const currentPage = computed(() => {
    return pageState.value.pages.find(page => page.id === pageState.value.currentPageId) || null
  })

  // 加载页面组件到画布
  const loadPageComponents = (pageId: string) => {
    const page = pageState.value.pages.find(p => p.id === pageId)
    if (page) {
      canvasState.value.components = JSON.parse(JSON.stringify(page.components))
      canvasState.value.selectedComponentIds = []
    }
  }

  // 创建新页面
  const createPage = (name?: string) => {
    // 保存当前页面
    if (pageState.value.currentPageId) {
      saveCurrentPageComponents()
    }

    const newPage: PageConfig = {
      id: uuidv4(),
      name: name || `页面${pageState.value.pages.length + 1}`,
      components: [],
      createdAt: Date.now(),
      updatedAt: Date.now()
    }

    pageState.value.pages.push(newPage)
    pageState.value.currentPageId = newPage.id
    
    // 清空画布
    canvasState.value.components = []
    canvasState.value.selectedComponentIds = []
    
    // 重置历史记录
    history.value = []
    historyIndex.value = -1
    saveHistory('创建页面')

    return newPage
  }

  // 切换页面
  const switchPage = (pageId: string) => {
    if (pageId === pageState.value.currentPageId) return

    // 保存当前页面
    if (pageState.value.currentPageId) {
      saveCurrentPageComponents()
    }

    // 切换到目标页面
    pageState.value.currentPageId = pageId
    loadPageComponents(pageId)
    
    // 重置历史记录
    history.value = []
    historyIndex.value = -1
    saveHistory('切换页面')
  }

  // 删除页面
  const deletePage = (pageId: string) => {
    const index = pageState.value.pages.findIndex(p => p.id === pageId)
    if (index === -1) return

    // 不能删除最后一个页面
    if (pageState.value.pages.length === 1) return

    pageState.value.pages.splice(index, 1)

    // 如果删除的是当前页面，切换到第一个页面
    if (pageState.value.currentPageId === pageId) {
      if (pageState.value.pages.length > 0) {
        switchPage(pageState.value.pages[0].id)
      } else {
        pageState.value.currentPageId = null
        canvasState.value.components = []
        canvasState.value.selectedComponentIds = []
      }
    }
  }

  // 重命名页面
  const renamePage = (pageId: string, newName: string) => {
    const page = pageState.value.pages.find(p => p.id === pageId)
    if (page) {
      page.name = newName
      page.updatedAt = Date.now()
    }
  }

  // 复制页面
  const duplicatePage = (pageId: string) => {
    const sourcePage = pageState.value.pages.find(p => p.id === pageId)
    if (!sourcePage) return

    const newPage: PageConfig = {
      id: uuidv4(),
      name: `${sourcePage.name} (副本)`,
      components: JSON.parse(JSON.stringify(sourcePage.components)),
      createdAt: Date.now(),
      updatedAt: Date.now()
    }

    pageState.value.pages.push(newPage)
    return newPage
  }

  // 初始化页面（如果没有页面则创建默认页面）
  const initPages = () => {
    if (pageState.value.pages.length === 0) {
      createPage('页面1')
    } else if (!pageState.value.currentPageId && pageState.value.pages.length > 0) {
      pageState.value.currentPageId = pageState.value.pages[0].id
      loadPageComponents(pageState.value.pages[0].id)
    }
  }

  return {
    canvasState,
    history,
    historyIndex,
    selectedComponent,
    selectedComponents,
    canUndo,
    canRedo,
    addComponent,
    removeComponent,
    removeSelectedComponents,
    updateComponent,
    selectComponent,
    selectMultipleComponents,
    moveComponent,
    resizeComponent,
    undo,
    redo,
    clearCanvas,
    importConfig,
    exportConfig,
    initHistory,
    alignComponents,
    distributeComponents,
    groupComponents,
    ungroupComponent,
    // 页面管理
    pageState,
    currentPage,
    createPage,
    switchPage,
    deletePage,
    renamePage,
    duplicatePage,
    initPages,
    saveCurrentPageComponents
  }
})
